#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include"model.h"

FILE OpenNew(char *name)
{
    char *name2 = malloc((sizeof(char))*strlen(name));
    char *temp = malloc((sizeof(char))*strlen(name));
    temp = name2;

    while (*name !='.')
    {
        *temp = *name;
        name = (name + 1);
    }

    strcat(name2,".png");
	 FILE *fp = fopen(name2,"a");
    return (*fp);
}

void DataToIHDR(data dt,FILE *fp)
{
    char sig[8] = "\x89PNG\r\n\x1A\n";
    fwrite(sig, 8, 1, fp);

    unsigned long int *length = malloc (sizeof(unsigned long int)); // int sur 4 octets
    *length = 13;
    char name[4] = "IHDR";

    unsigned long int *width = malloc (sizeof(unsigned long int)); // int sur 4 octets
	 unsigned long int *height = malloc (sizeof(unsigned  long int)); // int sur 4 octets
	 char *depth = malloc (sizeof(char)); // int sur 1 octet
	 char *colType = malloc (sizeof(char)); // int sur 1 octet
	 char *compression = malloc (sizeof(char)); // 1 octet
	 char *filter = malloc (sizeof(char)); // 1 octet
	 char *interlace = malloc (sizeof(char)); // 1 octet
    unsigned long int *crc = malloc (sizeof(unsigned long int)); // ecrit 0 sur 4 bit pour respecter la taille du IHDR.

    *width = dt->w;
    *height = dt->h;
    *depth = 16;
    *colType = 6;
    *compression = 0;
    *filter = 0;
    *interlace = 0;
    *crc = 0;

    fwrite(length, 4, 1, fp);
    fwrite(name, 4, 1, fp);
    fwrite(width, 4, 1, fp);
    fwrite(height, 4, 1, fp);
    fwrite(depth, 1, 1, fp);
    fwrite(colType, 1, 1, fp);
    fwrite(compression, 1, 1, fp);
    fwrite(filter, 1, 1, fp);
    fwrite(interlace, 1, 1, fp);
    fwrite(crc, 4, 1, fp); //ecrit 0 sur le crc
}

void DataToIDAT(data dt, FILE *fp)
{
    int size = (dt->w)*(dt->h);
    unsigned long int *length = malloc (sizeof(unsigned long int)); // length sur 4 octets
    unsigned long int *crc = malloc (sizeof(unsigned long int)); // CRC sur 4 octets
    *length = size;
    char name[4] = "IDAT";
    *crc = 0;

    fwrite(length, 4, 1, fp);
    fwrite(name, 4, 1, fp);
    fwrite(dt->ar, size, 1, fp);
    fwrite(crc, 4, 1, fp);
}

void IEND(FILE *fp)
{
    unsigned long int *length = malloc (sizeof(unsigned long int)); // length sur 4 octets
    unsigned long int *crc = malloc (sizeof(unsigned long int)); // CRC sur 4 octets
    *length = 0;
    char name[4] = "IEND";
    *crc = 0;

    fwrite(length, 4, 1, fp);
    fwrite(name, 4, 1, fp);
    fwrite(crc, 4, 1, fp);
}

int main ()
{
    return 0;
}
